# gozerbot/plugs/reload.py
#
#

""" reload plugin. """

## gozerlib imports

from gozerlib.utils.exception import handle_exception
from gozerlib.plugins import plugs
from gozerlib.commands import cmnds
from gozerlib.examples import examples
from gozerlib.aliases import aliasset
from gozerlib.admin import plugin_packages, savecmndtable, savepluginlist

## basic imports

import os
import sets

def handle_reload(bot, ievent):

    """ reload a plugin. """

    try:
        pluglist = ievent.args
    except IndexError:
        ievent.missing('<list plugins>')
        return

    reloaded = []
    errors = []

    for plug in pluglist:
        for package in plugin_packages:
            modname = "%s.%s" % (package, plug)
            try:
                plugs.reload(modname)
                reloaded.append(modname)
            except Exception, ex:
                errors.append(str(ex))
                if 'No module named' in str(ex):
                    continue

    if reloaded:
        ievent.reply('reloaded: ', reloaded, dot=True)
        return
    if errors:
        ievent.reply('errors: ', errors, dot=True)

cmnds.add('reload', handle_reload, 'OPER')
examples.add('reload', 'reload <plugin>', 'reload core')
#aliasset('load', 'reload')

#tests.add('reload country', 'country').add('unload country')

def handle_unload(bot, ievent):

    """ unload a plugin. """

    try:
        what = ievent.args[0].lower()
    except IndexError:
        ievent.missing('<plugin>')
        return

    if not plugs.exists(what):
        ievent.reply('there is no %s module' % what)
        return

    got = plugs.unload(what)

    ievent.reply("unloaded and disabled: ", got, dot=True)

cmnds.add('unload', handle_unload, 'OPER')
examples.add('unload', 'unload <plugin>', 'unload relay')
#tests.add('reload country').add('unload country', 'country')
